package br.gendi.rcp;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import br.gendi.beans.BaseGenomica;
import br.gendi.core.Conectividade;
import br.gendi.core.Util;
import br.gendi.dialog.IVisualizador;
import br.gendi.dialog.VisualizadorConsol;
import br.gendi.dialog.VisualizadorTabelas;

public class View extends ViewPart {

	private Label label1 = null;
	private Text textArea = null;
	private Button button1 = null;
	private Button button2 = null;
	private IVisualizador v = null;
	private Shell shell = null;

	public static final String ID = "br.gendi.rcp.view";

	public void createPartControl(final Composite parent) {
		shell = parent.getShell();
		GridData gridData6 = new GridData();
		gridData6.horizontalAlignment = GridData.BEGINNING;
		gridData6.verticalAlignment = GridData.CENTER;
		GridData gridData5 = new GridData();
		gridData5.horizontalAlignment = GridData.BEGINNING;
		gridData5.verticalAlignment = GridData.BEGINNING;
		GridData gridData4 = new GridData();
		gridData4.horizontalAlignment = GridData.FILL;
		gridData4.verticalAlignment = GridData.BEGINNING;
		GridData gridData3 = new GridData();
		gridData3.horizontalAlignment = GridData.FILL;
		gridData3.verticalAlignment = GridData.BEGINNING;
		GridData gridData2 = new GridData();
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.verticalAlignment = GridData.CENTER;
		gridData2.horizontalAlignment = GridData.FILL;
		GridData gridData1 = new GridData();
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.verticalAlignment = GridData.FILL;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.horizontalAlignment = GridData.FILL;
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.CENTER;
		gridData.horizontalSpan = 2;
		gridData.horizontalAlignment = GridData.FILL;
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 4;
		label1 = new Label(parent, SWT.NONE);
		label1.setText("Sequência genética:");
		label1.setLayoutData(gridData5);
		textArea = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
		textArea.setLayoutData(gridData1);
		textArea.setFont(new Font(parent.getDisplay(),"courier new",9 , SWT.NONE));
		button1 = new Button(parent, SWT.NONE);
		button1.setText("Buscar");
		button1.setImage(new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/stock-search.png")));
		button1.setLayoutData(gridData3);
		button2 = new Button(parent, SWT.NONE);
		button2.setText("Carregar arquivo");
		button2.setLayoutData(gridData4);
		button2.setImage(new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/gnome-fs-directory.png")));
		parent.setLayout(gridLayout);

		//buscar
		button1.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent e) {

			}

			public void widgetSelected(SelectionEvent e) {
				final String retorno = textArea.getText();
				if (retorno.length() == 0) {
					writeToStatusLine("Busca não realizada. Sistema aguardando.");
					MessageDialog.openInformation(shell, "EPIDI", "Nenhuma sequência foi digitada para poder realizar a busca.");
					return;
				}
				try{
					shell.setCursor(new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT));
					writeToStatusLine("Busca iniciada!");
					v = new VisualizadorConsol();
					//v = new VisualizadorConsolidador();
					//testes t3m = new testes();

					final ArrayList<Thread> threads = new ArrayList<Thread>();
					ArrayList<BaseGenomica> bases = Util.basesConfiguradas();
					int total = 0;
					if (bases == null) {
						MessageDialog.openInformation(shell, "EPIDI", "Não existem bases cadastradas para poder realizar a pesquisa.\nCadastre ao menos uma base e tente novamente.");
						writeToStatusLine("Busca não realizada!");
						return;
					}
					for (int i=0; i<bases.size(); i++) {
						final BaseGenomica base = bases.get(i);
						if (base.isAtivo() == false)
							continue;
						else
							total+=1;

						Thread operationThread = new Thread() {
							public void run() {

								String d = null;
								try {
									d = Conectividade.retornarHTMLGerar(retorno, base);
								} catch (Exception e) {
									e.printStackTrace();
									d = null;
									//System.out.println(e.toString());
								}
								if (d != null) {
									final String retD = d;
									shell.getDisplay().asyncExec(new Runnable() {
										public void run() {
											try {
												v.adicionar(base.getTitulo(), retD);
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									});
								} else {
									//MessageDialog.openError(shell, "EPIDI", "A base genomica " + base.getTitulo() + ", não executou a busca em um tempo mínimo!");
								}
							}
						};
						threads.add(operationThread);
					}
					for (int i=0;i<threads.size();i++)
						threads.get(i).start();

					boolean executando = false;
					while (executando != true) {
						for (int i=0;i<threads.size();i++) {
							if (threads.size()==0) {
								executando = true;
								break;
							}
							else {
								if (threads.get(i).isAlive()==false) {
									threads.remove(i);
								} 
							}
						}
						if (threads.size()==0) {
							break;
						}
					}
					MessageDialog.openInformation(shell, "EPIDI", "Busca finalizada.\nResultado na nova janela.");


					if (total == 0) { 
						MessageDialog.openInformation(shell, "EPIDI", "Não existem bases habilitadas para poder realizar a pesquisa.\nHabilite ao menos uma base e tente novamente.");
						writeToStatusLine("Busca não realizada!");
					} else
						writeToStatusLine("Busca finalizada!");
					shell.setCursor(new Cursor(shell.getDisplay(), SWT.CURSOR_ARROW));

				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		});

		//carregar arquivo
		button2.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent arg0) {

			}

			public void widgetSelected(SelectionEvent arg0) {

				FileDialog f = new FileDialog(new Shell());
				final String retorno = f.open();

				Thread operationThread = new Thread() {
					public void run() {
						final StringBuffer sb = new StringBuffer();

						if (retorno != null) {
							FileReader fReader = null;
							try {
								fReader = new FileReader(retorno);
							} catch (FileNotFoundException e) {
								e.printStackTrace();
							}
							try {
								int c;
								while ((c = fReader.read()) != -1) {
									sb.append((char)c);
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}

						shell.getDisplay().asyncExec(new Runnable() {
							public void run() {
								textArea.setText(sb.toString());
							}
						});
					}
				};
				operationThread.start();
				writeToStatusLine("Arquivo importado com sucesso.");
			}
		});
	}

	@Override
	public void setFocus() {
	}

	private void writeToStatusLine(String aMessage) {
		final String msg = aMessage;

		getViewSite().getShell().getDisplay().asyncExec (new Runnable () {
			public void run () {
				getViewSite().getActionBars().getStatusLineManager().setMessage(msg);
			}
		});
	}

}
